//
//  MVCDataSource.m
//  Advance_MVC
//
//  Created by Willian on 2021/5/2.
//

#import "MVCDataSource.h"

@interface MVCDataSource () <UITableViewDelegate, UITableViewDataSource>

//UI -> Model的代理通道
@property (nonatomic, weak) id<PresentDelegate> delegate;
@property (nonatomic, copy) ConfigCellBlock configCellBlock;
@property (nonatomic, copy) NSString *cellReuseId;

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MVCDataSource

- (instancetype)initWithActionTarget:(id<PresentDelegate>)actionTarget withCellReuseId:(NSString *)cellReuseId withConfigCellBlock:(ConfigCellBlock)configCellBlock{
    self = [super init];
    if (self) {
        self.delegate = actionTarget;
        self.cellReuseId = cellReuseId;
        self.configCellBlock = configCellBlock;
    }
    return self;
}

- (void)obtainDataArray:(NSMutableArray *)dataArray{
    _dataArray = dataArray;
}


#pragma mark - UITableViewDataSource
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellReuseId forIndexPath:indexPath];
    
    __weak MVCDataSource *weakSelf = self;
    if (self.configCellBlock) {
        __strong  MVCDataSource *strongSelf = weakSelf;
        strongSelf.configCellBlock(cell, strongSelf.dataArray[indexPath.row], indexPath);
    }
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //选中某一行的回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectCellWithIndex:)]) {
        [self.delegate selectCellWithIndex:indexPath.row];
    }
}

@end
